package net.wendal.nutzbook.module;

import net.wendal.nutzbook.bean.User;
import net.wendal.nutzbook.bean.UserProfile;
import net.wendal.nutzbook.service.UserService;
import net.wendal.nutzbook.util.Toolkit;
import org.apache.shiro.SecurityUtils;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.integration.shiro.SimpleShiroToken;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.util.NutMap;
import org.nutz.mvc.Scope;
import org.nutz.mvc.annotation.*;
import org.nutz.mvc.filter.CheckSession;

import javax.servlet.http.HttpSession;
import java.util.Date;
@Filters(@By(type=CheckSession.class, args={"me", "/"}))//含义是,如果当前Session没有带me这个attr,就跳转到/页面,即首页.
@IocBean
@At("/user")
@Ok("json:{locked:'password|salt',ignoreNull:true}")
public class UserModule extends BaseModule{
	@Inject
	protected UserService userService;
	
	@At
	public int count() {
		return dao.count(User.class);
	}

	@GET
	@At("/login")
	@Filters
	@Ok("jsp:jsp.user.login") // 降内部重定向到登录jsp
	public void loginPage() {}

	@At
	@Filters()//为login方法设置为空的过滤器,不然就没法登陆了
	public Object login(@Param("username")String name,
						@Param("password")String password,
						@Param("captcha")String captcha,
						@Attr(scope = Scope.SESSION,value = "nutz_captcha")String _captcha,
						HttpSession session) {
		NutMap re = new NutMap();
		if(!Toolkit.checkCaptcha(_captcha,captcha)){
			return re.setv("ok",false).setv("msg","验证码错误");
		}
		int userId = userService.fetch(name,password);
		if(userId<0) {
			System.out.println(userId);
			return re.setv("ok", false).setv("msg", "用户名或密码错误");
		}else {
			session.setAttribute("me", userId);
			// 完成nutdao_realm后启用.
			 SecurityUtils.getSubject().login(new SimpleShiroToken(userId));
			return re.setv("ok",true);
		}
	}
	
	@At
    @Ok(">>:/")
    public void logout(HttpSession session) {
        session.invalidate();
    }
	
	protected String checkUser(User user,boolean create) {
		if(user==null) {
			return "空对象";
		}
		
		if(create) {
			if(Strings.isBlank(user.getName())||Strings.isBlank(user.getPassword()))
				return "用户名/密码不能为空";
		}else {
			if(Strings.isBlank(user.getPassword()))
				return "密码不能为空";
		}
		
		String passwd = user.getPassword().trim();
		if(6>passwd.length()||passwd.length()>12) 
			return "密码长度错误";
		user.setPassword(passwd);
		
		if(create) {
			int count = dao.count(User.class, Cnd.where("name","=",user.getName()));
			if(count!=0) {
				return "用户名已经存在";
			}
			
		}else {
			if(user.getId()<1) {
				return "用户Id非法";
			}
		}
		if(user.getName()!=null)
			user.setName(user.getName().trim());
		return null;
	}
	
	
	 @At
	    public Object add(@Param("..")User user) {
	        NutMap re = new NutMap();
	        String msg = checkUser(user, true);
	        if (msg != null){
	            return re.setv("ok", false).setv("msg", msg);
	        }
	        user.setCreateTime(new Date());
	        user.setUpdateTime(new Date());
	        user = userService.add(user.getName(),user.getPassword());
	        return re.setv("ok", true).setv("data", user);
	    }

	    @At
		public Object update(@Param("password") String password,@Attr("me")int me){

		if (Strings.isBlank(password)||password.length()<6)
			return new NutMap().setv("ok",false).setv("msg","密码不符合要求");
		userService.updatePassword(me,password);
		return new NutMap().setv("ok",true);
		}
	 
	   /* @At
	    public Object update(@Param("..")User user) {
	        NutMap re = new NutMap();
	        String msg = checkUser(user, false);
	        if (msg != null){
	            return re.setv("ok", false).setv("msg", msg);
	        }
	        user.setName(null);// 不允许更新用户名
	        user.setCreateTime(null);//也不允许更新创建时间
	        user.setUpdateTime(new Date());// 设置正确的更新时间
	        dao.updateIgnoreNull(user);// 真正更新的其实只有password和salt
	        return re.setv("ok", true);
	    }*/
	    
	    @At
	    @Aop(TransAop.READ_COMMITTED)
	    public Object delete (@Param("id")int id,@Attr("me")int me) {
	    	if(me ==id) {
	    		return new NutMap().setv("ok", false).setv("msg", "不能删除当前用户！！");
	    	}
	    	dao.delete(User.class, id);
	    	dao.clear(UserProfile.class,Cnd.where("userId", "=", me));
	    	return new NutMap().setv("ok", true);
	    }
	    
	    @At
	    public Object query(@Param("name")String name,@Param("..")Pager pager) {
	    	Cnd cnd = Strings.isBlank(name)?null:Cnd.where("name", "like", "%"+name+"%");
	    	QueryResult qr = new QueryResult();
	    	qr.setList(dao.query(User.class, cnd, pager));
	    	pager.setRecordCount(dao.count(User.class,cnd));
	    	qr.setPager(pager);
	    	return qr;
	    }
	    
	    /**
	     * 因为我们打算把jsp放在WEB-INF下,然后WEB-INF下的文件是不能直接访问的,所以加个跳转的方法
	     */
	    @At("/")
	    @Ok("jsp:jsp.user.list") // 真实路径是 /WEB-INF/jsp/user/list.jsp
	    public void index() {
	    }
	    
	    
	    
}
